#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File    :   task_sched.py
@Time    :   2023/04/12 15:59:48
@Author  :   youle
@Email   :   a_fly0505@163.com
@Copyright : 侵权必究
'''


from __future__ import annotations
import core.config as config
from datetime import datetime, date
import sched
import time
import threading
from concurrent.futures import ThreadPoolExecutor


class TimerThread(threading.Thread):
    # (self, group: None = None, target: Callable[..., object] | None = None, name: str | None = None, args: Iterable[Any] = ..., kwargs: Mapping[str, Any] | None = None, *, daemon: bool | None = None)
    def __init__(self, config:Config, group=None, target=None, name=None, args=..., kwargs=None, *, daemon=None) -> None:
        super().__init__(group, target, name, args, kwargs, daemon=daemon)
        # 自有逻辑
        self._config = config
        self._schedule = sched.scheduler()
        self.mutex = threading.Lock()

    def run(self):
        """跑fund rsi"""
        self.RunFundTask()

        """跑stock rsi"""
        self.RunStockTask()
        self._schedule.run()

    def stop(self)->None:
        self.mutex.acquire()
        for event in self._schedule.queue:
            self._schedule.cancel(event)
        self.mutex.release()

    def FundRSIFunc(self, interval:float, name:str, codes:list[str])->None:
        #
        print("=======run {} {} {}========".format(interval, name, codes))
        self.mutex.acquire()
        self._schedule.enter(delay=interval, priority=0, action=self.FundRSIFunc, argument=(interval, name, codes))
        self.mutex.release()

    def RunFundTask(self) -> None:
        name:str = "T+0"
        interval = 3 #self._config.poll_data[""]
        codes:list[str] = ["99999"]
        self._schedule.enter(delay=interval, priority=0, action=self.FundRSIFunc, argument=(interval, name, codes))

    def RunStockTask(self) -> None:
        pass


class TaskSched():
    def __init__(self, config: config.Config) -> None:
        self._time_thread = TimerThread(config)

    def Run(self):
        self._time_thread.start()

    def Stop(self):
        self._time_thread.stop()
        self._time_thread.join()


if __name__ == "__main__":
    config.g_config.LoadConfig("/home/youle/stock/config")
    sched_task = TaskSched(config.g_config)
    sched_task.Run()
    time.sleep(10)
    sched_task.Stop()
